package com.centling.smartSealForPhone.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.adapter.BossModeListAdapter;
import com.centling.smartSealForPhone.bean.BossModeInfo;
import com.centling.smartSealForPhone.bean.DeviceTypeBean;
import com.centling.smartSealForPhone.bean.LoginBean;
import com.centling.smartSealForPhone.constants.GlobalData;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.wsdk.service.BluetoothLeService;
import com.centling.smartSealForPhone.utils.BlueToothScanUtil;
import com.centling.smartSealForPhone.utils.ControlUtil;
import com.centling.smartSealForPhone.utils.LogUtil;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.ParseBluetoothData;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.widget.AutoRecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

public class BossModeActivity extends TitleBarActivity implements BlueToothScanUtil.StopSearchListener {
    private static final int OPEN_BLUE_DIALOG = 1000;

    private List<BossModeInfo> list = new ArrayList<>();
    private int pageIndex;
    private String bossApplyId;
    private DeviceTypeBean deviceTypeBean;
    private PtrClassicFrameLayout ptrUnlockList;
    private AutoRecyclerView rvUnlock;

    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                mProcessDialog.dismiss();
                if (BuildConfig.DEBUG) {
                    ShowToast.shortTime("Boss Mode Connected");
                }
                GlobalData.isConnect = true;
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                if (ParseBluetoothData.isOpenBoss(data)) {
                    Map<String, String> param = new HashMap<>();
                    putJsonEnqueue(UrlConstants.BOSSMODE_BEGIN + bossApplyId + "/begin", param, new OkHttpUtil.NetCallBack() {
                        @Override
                        public void onSucceed(String json) {
                            ShowToast.shortTime("解锁模式开启成功");
                            sendRequestToGetStampList(true);
                        }

                        @Override
                        public void onFailed(String reason) {
                            ShowToast.shortTime(reason);
                        }
                    });
                } else if (ParseBluetoothData.isWorkMode(data)) {
                    Map<String, String> param = new HashMap<>();
                    putJsonEnqueue(UrlConstants.BOSSMODE_BEGIN + bossApplyId + "/end", param, new OkHttpUtil.NetCallBack() {
                        @Override
                        public void onSucceed(String json) {
                            ShowToast.shortTime("解锁模式关闭成功");
                            sendRequestToGetStampList(true);
                        }

                        @Override
                        public void onFailed(String reason) {
                            ShowToast.shortTime(reason);
                        }
                    });
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_boss_mode);

        LoginBean loginBean = new Gson().fromJson(SPUtil.getString(SPConstants.LOGIN_JSON), LoginBean.class);
        macAddress = loginBean.getEquipRegisterInfo().getBlueToothMac();
        sn = SPUtil.getString(SPConstants.CORE_SN);

        if (TextUtils.isEmpty(macAddress)) {
            ShowToast.shortTime("获取用户绑定设备信息失败");
            finish();
        }

        setTitleBarText("解锁模式列表");
        setTitleBarRightPadding(R.drawable.iv_add_plus);
        setTitleBarRightClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BossModeActivity.this, ApplyBossModeActivity.class);
                startActivity(intent);
            }
        });

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        registerReceiver(bluetoothReceiver, intentFilter);

        initView();
    }

    public void initView() {
        ptrUnlockList = (PtrClassicFrameLayout) findViewById(R.id.ptr_unlock_list);
        rvUnlock = (AutoRecyclerView) findViewById(R.id.rv_unlock_list);

        BossModeListAdapter adapter = new BossModeListAdapter(BossModeActivity.this, list);
        rvUnlock.setLayoutManager(new GridLayoutManager(this, 1));
        rvUnlock.setAdapter(adapter);
        ptrUnlockList.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                sendRequestToGetStampList(true);
            }
        });

        rvUnlock.setLoadDataListener(new AutoRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                sendRequestToGetStampList(false);
            }
        });

        adapter.setOnBossModeBeginListener(new BossModeListAdapter.OnBossModeBeginListener() {
            @Override
            public void onClick(BossModeInfo item) {
                if (!BlueToothScanUtil.isBlueToothOpened()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, OPEN_BLUE_DIALOG);
                    return;
                }
                if (GlobalData.isConnect) {
                    if ("0".equals(GlobalData.selfCheckStatus)) {
                        LogUtil.d(GlobalData.isConnect + "");
                        bossApplyId = item.getBossId();
                        sendRequestToCheckIsBoss();
                    } else {
                        ShowToast.shortTime("设备异常，请联系管理员! ");
                    }
                } else {
                    ShowDialog.showSelectDialog(mContext, "重新连接蓝牙", "蓝牙未连接，请先连接蓝牙", "", new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            mProcessDialog.setTitle("正在连接蓝牙").showNormal();
                            blueToothScanUtil.setMacAddress(macAddress);
                            blueToothScanUtil.startSearchBlueDevice();
                            blueToothScanUtil.setStopSearchListener(BossModeActivity.this);
                        }
                    });
                }
            }
        });

        adapter.setOnBossModeEndListener(new BossModeListAdapter.OnBossModeEndListener() {
            @Override
            public void onClick(BossModeInfo item) {
                if (!BlueToothScanUtil.isBlueToothOpened()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, OPEN_BLUE_DIALOG);
                    return;
                }
                if (GlobalData.isConnect) {
                    if ("0".equals(GlobalData.selfCheckStatus)) {
                        LogUtil.d(GlobalData.isConnect + "");
                        bossApplyId = item.getBossId();
                        sendRequestToCheckIsBossEnd();
                    } else {
                        ShowToast.shortTime("设备异常，请联系管理员! ");
                    }
                } else {
                    ShowDialog.showSelectDialog(mContext, "重新连接蓝牙", "蓝牙未连接，请先连接蓝牙", "", new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            mProcessDialog.setTitle("正在连接蓝牙").showNormal();
                            blueToothScanUtil.setMacAddress(macAddress);
                            blueToothScanUtil.startSearchBlueDevice();
                            blueToothScanUtil.setStopSearchListener(BossModeActivity.this);
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!BlueToothScanUtil.isBlueToothOpened()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, OPEN_BLUE_DIALOG);
        } else {
            ptrUnlockList.post(new Runnable() {
                @Override
                public void run() {
                    ptrUnlockList.autoRefresh();
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bluetoothReceiver);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_BLUE_DIALOG && resultCode == Activity.RESULT_CANCELED) {
            finish();
        }

    }

    private void sendRequestToGetStampList(final boolean isRefresh) {
        if (isRefresh) {
            pageIndex = 0;
        }
        getEnqueue(UrlConstants.BOSS_MODE_LIST + pageIndex, new OkHttpUtil.NetCallBack() {

            @Override
            public void onSucceed(String json) {
                JSONObject data;
                try {
                    data = new JSONObject(json);
                    int pageSize = Integer.parseInt(data.get("size").toString());
                    if (isRefresh) {
                        list.clear();
                        rvUnlock.setLoadDataListener(new AutoRecyclerView.LoadDataListener() {
                            @Override
                            public void onLoadMore() {
                                sendRequestToGetStampList(false);
                            }
                        });
                    }
                    List<BossModeInfo> tempList;
                    tempList = new Gson().fromJson(data.getJSONArray("rows").toString(), new TypeToken<List<BossModeInfo>>() {
                    }.getType());
                    list.addAll(tempList);
                    rvUnlock.getAdapter().notifyDataSetChanged();
                    if (list.size() < pageSize) {
                        rvUnlock.loadMoreComplete(true);
                    } else {
                        rvUnlock.loadMoreComplete(false);
                    }
                    ptrUnlockList.refreshComplete();
                    pageIndex++;
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailed(String reason) {
                ShowToast.shortTime(reason);
                ptrUnlockList.refreshComplete();
                rvUnlock.loadMoreComplete(false);
            }
        });
    }

    private void sendRequestToCheckIsBoss() {
        getEnqueue(UrlConstants.GET_DEVICE_STATE + GlobalData.BOSSMODE, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                deviceTypeBean = new Gson().fromJson(json, DeviceTypeBean.class);
                if (deviceTypeBean.isAllowed()) {
                    new ControlUtil().openBoss();
                } else {
                    ShowToast.shortTime(deviceTypeBean.getMessage());
                }
            }

            @Override
            public void onFailed(String reason) {
                ShowToast.shortTime(reason);
            }
        });
    }

    private void sendRequestToCheckIsBossEnd() {
        getEnqueue(UrlConstants.GET_DEVICE_STATE + GlobalData.BOSSMODEEND, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                deviceTypeBean = new Gson().fromJson(json, DeviceTypeBean.class);
                if (deviceTypeBean.isAllowed()) {
                    new ControlUtil().closeBoss();
                } else {
                    ShowToast.shortTime(deviceTypeBean.getMessage());
                }
            }

            @Override
            public void onFailed(String reason) {
                ShowToast.shortTime(reason);
            }
        });
    }

    @Override
    public void onStopped(boolean timeout) {
        mProcessDialog.dismiss();
        if(timeout) {
            ShowToast.shortTime("连接设备失败");
        }
    }
}
